

import 'package:bookshelf/event/read_block_event.dart';

import '../event/inventory_event.dart';
import '../main.dart';
import '../util/analysis_book_rule.dart';
import '../util/convert_util.dart';

class ResultHandler{

  String ip = "";
  String result = "";
  bool isAnalyze = false;

  Set<(String,String,String)> set = {};

  dataReceived(hexString,ip){
    this.ip = ip;
    //沾包
    if(!hexString.startsWith('DD11') && result.isNotEmpty){
      result += hexString;
      analyze();
      return;
    }

    //询查标签
    if(hexString.length > 12 && hexString.substring(10,12) == "01"){
      result += hexString;
      analyze();
      return;
    }
    //读块
    if(hexString.length > 12 && hexString.substring(10,12)=="23"){
      analyzeBlock(hexString);
      return;
    }
  }

  analyze(){

    print('result=$result');
    if(isAnalyze){
      return;
    }
    isAnalyze = true;
    //盘点结束指令
    if(result.startsWith("DD11EF0C") && result.length>=24){
      var data = set.toList();
      eventFactory.fire(InventoryEvent(data));
      result = "";
      set.clear();
      isAnalyze = false;
      return;
    }
    if(result.length>=38){
      set.add((result.substring(18,34),result.substring(8,10),ip));
      result = result.substring(38);
      isAnalyze = false;
      if(result.isNotEmpty){
        analyze();
      }
    }else{
      isAnalyze = false;
    }
  }

  analyzeBlock(hexString) {
    if (hexString.length > 14 && hexString.substring(12, 14) == "95") {
      eventFactory.fire(ReadBlockEvent(null));
      return;
    }
    String blockCount = hexString.substring(12, 14);
    int count = hexToInt(blockCount);
    if (hexString.length >= 16+count*2+count*8+4) {
      var block = '';
      for(int i = 0; i<count;i++){
        int start = 16+(i+1)*2+i*8;
        block = block + hexString.substring(start,start+8);
      }
      var no = analysisBookRule(block);
      eventFactory.fire(ReadBlockEvent(no));
    }else{
      eventFactory.fire(ReadBlockEvent(null));
    }
  }

}